import { Action } from "routing-controllers";
import { verify } from 'jsonwebtoken';
import { createHash } from "crypto";
import fs from 'fs';
import { basename, extname } from "path";

const { APP_SECRET } = process.env

export function getFilenameWithoutExtension(filepath: string): string {
    return basename(filepath, extname(filepath));
}

export async function getAuthorizationChecker(action: Action) {
    const authorization: string = action.request.headers['authorization'];

    if (!authorization) return;

    const [type, token] = authorization.split(/\s+/);

    try {
        const obj = verify(token, `${APP_SECRET}`);
        if (obj) return obj;
    } catch {
        return;
    }
}

export function encrypt(raw: string) {
    return createHash('sha1')
        .update(APP_SECRET + raw)
        .digest('hex');
}

export function chunkArray(array: any[], chunkSize: number): any[][] {
    let result: any[][] = [];
    for (let i = 0; i < array.length; i += chunkSize) {
        let chunk = array.slice(i, i + chunkSize);
        result.push(chunk);
    }
    return result;
}

export async function createDirectoryIfNotExists(directory: string): Promise<void> {
    try {
        await fs.promises.access(directory, fs.constants.R_OK | fs.constants.W_OK);
    } catch (error: any) {
        if (error.code === 'ENOENT') {
            try {
                await fs.promises.mkdir(directory, { recursive: true });
            } catch (mkdirErr) {
                console.error('Error creating directory:', mkdirErr);
            }
        } else {
            console.error('Unexpected error:', error);
        }
    }
}